/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2012-10-15         luwei
 */

package com.tianci.appstore.utils;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    private static ThreadPoolExecutor threadPoolManager = null;
    private static BlockingQueue<Runnable> workQueue = null;

    public static void addTask(Runnable task) {
        generateThreadPool();
        if (task != null) {
            threadPoolManager.execute(task);
        }
    }

    public static void addTasks(List<Runnable> tasks) {
        generateThreadPool();
        if (tasks != null) {
            threadPoolManager.getQueue().addAll(tasks);
        }
    }

    private static void generateThreadPool() {
        if (threadPoolManager == null) {
            // 无限任务队列，这种情况有可能会资源耗尽，但是不会取消任务
            workQueue = new LinkedBlockingDeque<Runnable>();
            // 最大10（corePoolSize）个线程的线程池，因为为无限队列，因此maxmumPoolSize没有用
            threadPoolManager = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, workQueue);
        }
    }

    public static void cancelAll() {
        if (workQueue != null) {
            if (!workQueue.isEmpty()) {
                workQueue.clear();
            }
        }
    }

    public static void shutDownThreadPool() {
        if (threadPoolManager != null) {
            cancelAll();
            threadPoolManager.shutdown();
            threadPoolManager = null;
            workQueue = null;
        }
    }
}
